package plugin.demo.runner.apt.config.load;

import org.springframework.boot.env.YamlPropertySourceLoader;
import org.springframework.core.env.PropertiesPropertySource;
import org.springframework.core.env.PropertySource;
import org.springframework.core.io.Resource;
import org.springframework.core.io.support.DefaultPropertySourceFactory;
import org.springframework.core.io.support.EncodedResource;
import org.springframework.core.io.support.PropertySourceFactory;

import java.io.IOException;
import java.io.UnsupportedEncodingException;
import java.util.List;
import java.util.Properties;

/**
 * @Author: Qiao Hang
 * @CreateDate: 2021/5/21 上午11:21
 * @UpdateDate:
 * @Description:
 */
public class YmlPropertiesLoadFactory extends DefaultPropertySourceFactory {
    @Override
    public PropertySource<?> createPropertySource(String name, EncodedResource resource) throws IOException {
        if (resource == null) {
            return super.createPropertySource(name, resource);
        }else if(!resource.getResource().getFile().exists()){
            return new PropertiesPropertySource(null,new Properties());
        }else if(resource.getResource().getFile().getName().endsWith(".yml")
                || resource.getResource().getFile().getName().endsWith(".yaml")){
            List<PropertySource<?>> load = new YamlPropertySourceLoader().load(
                    resource.getResource().getFile().getName(),
                    resource.getResource()
            );
            return load.get(0);
        }else {
            throw new UnsupportedEncodingException("文件格式不支持.");
        }
    }
}
